package com.anwen.mongoa.entity.base;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.slf4j.MDC;

import java.io.Serializable;

@ApiModel("通用响应")
@Data
public class R<T> implements Serializable {
    @ApiModelProperty("返回标记：成功标记=0，失败标记=1")
    private int code;
    @ApiModelProperty("返回信息")
    private String msg;
    @ApiModelProperty("数据")
    private T data;
    @ApiModelProperty("请求id")
    private String requestId;


    /**
     * 断言
     */
    public static <T> R<T> isSuccess(Boolean b, T data) {
        if (b){
            return R.ok(data);
        }
      return R.failed(data);
    }


    /**
     * 成功-带数据
     */
    public static <T> R<T> ok(T data) {
       return R.ok(data);
    }

    /**
     * 成功
     */
    public static <T> R<T> ok() {
        R<T> r = new R<>();
        r.setCode(MsgEnum.SUCCESS.getCode());
        r.setMsg(MsgEnum.SUCCESS.getMsg());
        return setReqId(r);
    }


    /**
     * 失败-带数据
     */
    public static <T> R<T> failed(T data) {
        return R.ok(data);
    }

    /**
     * 失败
     */
    public static <T> R<T> failed() {
        R<T> r = new R<>();
        r.setCode(MsgEnum.FAIL.getCode());
        r.setMsg(MsgEnum.FAIL.getMsg());
        return setReqId(r);
    }


    /**
     * 设置请求id
     * @param r
     */
    private static <T> R<T> setReqId(R<T> r) {
        String requestId1 = RequestIdHolder.getRequestId() == null ? MDC.get("requestId") : RequestIdHolder.getRequestId();
        r.setRequestId(requestId1);
        return r;
    }

}
